package com.hk.servlet.company;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hk.model.Nav;
import com.hk.model.NewsType;
import com.hk.model.vo.Result;
import com.hk.service.INavService;
import com.hk.service.impl.NavServiceImpl;
import com.hk.utils.CharacterEncoding;
import com.hk.utils.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: zhe
 * @Date: 2021/6/21 15:31
 * @Statement: 通过id查询单独导航或修改导航信息
 */
@WebServlet("/nav/NavFindByIdOrUpdate")
public class NavFindByIdOrUpdateServlet extends HttpServlet {

    INavService iNavService = new NavServiceImpl();

    /**
     * 通过Id修改单独导航信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        String id = Tool.nullToString(req.getParameter("id"));
        Nav nav = iNavService.findById(Tool.parseInt(id));
        PrintWriter out = resp.getWriter();
        String navJSON = JSONObject.toJSONString(nav);
        out.println(navJSON);
        out.flush();
        out.close();

    }

    /**
     * 修改导航信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        BufferedReader reader = req.getReader();
        Gson gson = new Gson();
        Nav nav = gson.fromJson(reader, Nav.class);
        if (nav == null) {
            nav = new Nav();
        }
        PrintWriter out = resp.getWriter();
        Result result = new Result();
        if (nav.getId() <= 0) {
            result.setStatus(0);
            result.setMessage("error");
            String resultJSON = JSONObject.toJSONString(result);
            out.println(resultJSON);
            out.flush();
            out.close();
        }
        int update = iNavService.update(nav);
        if (update != 1) {
            result.setStatus(update);
            result.setMessage("error");
        } else {
            result.setStatus(update);
            result.setMessage("success");
        }
        String resultJSON = JSONObject.toJSONString(result);
        out.println(resultJSON);
        out.flush();
        out.close();

    }


}
